<?php

namespace App\Http\Controllers\Commands;

use App\Consts\ExceptionCodeConst;
use App\Consts\GlobalConst;
use App\Services\RabbitMQService;
use Illuminate\Http\Request;

/**
 * RabbitMQ 外部命令
 * Class CommandController
 * @package App\Http\Controllers\Api
 */
class RabbitMQController extends CommandController
{

    /** @var array $asyncList */
    public $asyncList = ['work', 'reload'];

    /**
     * Run command
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \Exception
     */
    public function run(Request $request)
    {
        return parent::run($request);
    }

    /**
     * 启动 MQ - sync : false
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \Exception
     */
    public function start(Request $request)
    {
        return $this->exec($request, 'startMq');
    }

    /**
     * 停止 MQ
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \Exception
     */
    public function stop(Request $request)
    {
        return $this->exec($request, 'stopMq');
    }

    /**
     * 重启 MQ - sync : false
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \Exception
     */
    public function reload(Request $request)
    {
        return $this->exec($request, 'reloadMq');
    }

    /**
     * exec command
     * @param Request $request
     * @param $method
     * @return \Illuminate\Http\JsonResponse|void
     * @throws \Exception
     */
    protected function exec(Request $request, $method)
    {
        $code = $request->get('code', '');
        if ($code != md5(md5(GlobalConst::SECRET_MSG_CENTER))) {
            throw new \Exception(lang('Not Found'), ExceptionCodeConst::ROUTE_NOT_FOUND);
        }
        if ($method === 'reloadMq') {
            $res = RabbitMQService::reloadMq();
        } elseif ($method === 'startMq') {
            $res = RabbitMQService::startMq();
        } elseif ($method === 'stopMq') {
            $res = RabbitMQService::stopMq();
        } else {
            throw new \Exception(lang('Not Found'), ExceptionCodeConst::ROUTE_NOT_ALLOWED);
        }
        if (isset($res['code'])) {
            return $this->errorReturn($res['msg'], $res['code']);
        }
        return $this->apiReturn($res);
    }

}